import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Affix, Button, Form, message } from 'antd';
import { messages } from 'share/common';
import Priority from 'components/template/priority';
import 'styles/expense-reimbursement-control/mileage-subsidy/new-mileage-subsidy.scss';
import { formData } from 'containers/expense-reimbursement-control/new-mileage-subsidy/dataSources';
import mileageService from 'containers/expense-reimbursement-control/new-mileage-subsidy/mileage-service';
import { permission } from 'containers/finance-setting/permisson';

@connect(mapStateToProps)
@permission
class NewLadderRule extends Component {

  static propTypes = {};

  state = {
    priority: void 0,
    formList: {
      'enabled': { initData: true, valuePropName: 'checked' },
      'ruleDesc': {},
      'stepMileage': { initData: [0, -1] },
    }, // 表单项
    submitLoading: false
  };

  componentWillMount() {
    this.handleInit();
  }

  handleInit = () => {
    // 初始化
    const { formList } = this.state;
    const { params, params: { levelCode, levelOrgId, levelOrgName, companies, stepMileageOptId, stepVOs, companyNameList, setOfBook } } = this.props;
    let { priority = {} } = this.state;
    if (!stepMileageOptId) {
      this.setState({
        priority: {
          levelCode: 'SET_OF_BOOK',
          levelOrgId: setOfBook.id,
          levelOrgName: setOfBook.name
        }
      });
      return;
    }
    Object.keys(formList)
      .map(item => {
        if (params[item] !== null && params[item] !== void 0) {
          formList[item].initData = params[item];
        }
      });
    priority.distribution = {};
    stepVOs.forEach((item, index) => {
      index !== 0 && formList.stepMileage.initData.splice(formList.stepMileage.initData.length - 1, 0, item.startUnit);
    });
    companies && (priority.distribution.companies = companies.map((item, index) => {
      return {
        name: companyNameList[index],
        id: item
      };
    }));
    priority = { ...priority, levelCode, levelOrgId, levelOrgName };
    this.setState({ priority, formList });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { priority, priority: { distribution }  } = this.state;
    const { params } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (!priority || !priority.levelCode) {
          message.error(messages('expense-12.key153')/*请选择所属组织*/);
          return;
        }
        if(priority && (priority.levelCode === 'SET_OF_BOOK') && priority.distribution && priority.distribution.companies &&
          !priority.distribution.companies.length) {
          message.error(messages('expense-12.key150')/*请选择启用公司*/);
          return;
        }
        this.setState({ submitLoading: true });
        distribution && distribution.companies && (priority.companies = distribution.companies.map(item => item.id));
        delete priority.distribution;
        delete params.companies;
        mileageService.addLadderRule({ ...params, ...values, ...priority })
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close('rule');
          })
          .finally(() => {
            this.setState({ submitLoading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.props.close(false);
  };

  handlePriority = (priority) => {
    this.setState({ priority });
  };

  renderForm = () => {
    const { formList, priority } = this.state;
    const { form: { getFieldDecorator }, params: { readOnly, stepMileageOptId } } = this.props;
    const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 10, offset: 0 } };
    const formArray = Object.keys(formList)
      .map(item => {
        const middleForm = formData[item], stepMileageLayout = {};
        const { name, child, params = {}, required, component, extra } = middleForm;
        params.disabled = readOnly || this.isReadOnly();
        if (item === 'stepMileage') {
          stepMileageLayout.labelCol = { span: 0 };
          stepMileageLayout.wrapperCol = { span: 24 };
        }
        return (
          <Form.Item  {...stepMileageLayout} extra={extra} label={name}>
            {
              getFieldDecorator(item, {
                rules: [{
                  required: !!required,
                  message: messages('expense-12.key154',{arg1: name})/*请填写{arg1}*/
                }],
                initialValue: formList[item].initData,
                valuePropName: formList[item].valuePropName || 'value'
              })(React.createElement(component, params, child))
            }
          </Form.Item>
        );
      });

    formArray.splice(1, 0, (
      <Priority
        top={'SET_OF_BOOK'}
        single={false}
        onChange={this.handlePriority}
        showCompany
        companyProps={{
          disabled: (readOnly || !!stepMileageOptId)
        }}
        disabledTop={!!stepMileageOptId}
        defaultValue={priority}
        formItemLayout={formItemLayout}
        required
      />
    )); // 权限套装直接插入Item list
    return formArray;
  };


  render() {
    const { submitLoading } = this.state;
    const { params: { readOnly } } = this.props;
    return (
      <section className='new-unit new-form'>
        <Form onSubmit={this.handleSubmit}>
          {
            this.renderForm()
          }
          <div className="slide-footer">
            <Button
              type="primary"
              disabled={this.isReadOnly() || readOnly}
              htmlType="submit"
              loading={submitLoading}>
              {messages('common.save')/*保存*/}
            </Button>
            <Button
              onClick={this.handleCancel}
              disabled={this.isReadOnly() || readOnly}
              className="new-unit-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </div>
        </Form>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

const WrappedNewUnit = Form.create()(NewLadderRule);

export default WrappedNewUnit;
